package controller;


import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.*;
import entity.*;

import service.*;



import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/schoolRead.ctl")
public class SchoolReadCtl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        JSONObject message = new JSONObject();

        String id_str = request.getParameter("id");
        try{
            Long id = Long.parseLong(id_str);
            School school =
                    SchoolService.getInstance().find(id);
            String school_json = JSON.toJSONString(school, JSONWriter.Feature.ReferenceDetection);

            response.getWriter().println(school_json);
        } catch (SQLException e){
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }catch (Exception e){
            message.put("message", "网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }finally {
            response.getWriter().close();
        }
    }


    protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        JSONObject message = new JSONObject();

        try {
            Collection<School> schools = SchoolService.getInstance().findAll();

            String school_json = JSON.toJSONString(schools,JSONWriter.Feature.ReferenceDetection);
            response.getWriter().println(school_json);
        } catch (SQLException e){
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }catch (Exception e){
            message.put("message", "网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }finally {
            response.getWriter().close();
        }
    }
}
